package com.xxx.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.xxx.autoconfig.sms.SmsTemplate;
import com.xxx.domain.db.User;
import com.xxx.service.db.UserService;
import com.xxx.util.ConstantUtil;
import com.xxx.util.JwtUtil;
import com.xxx.vo.ErrorResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Component  // 加入springmvc容器
public class UserManager {

    @DubboReference
    UserService userService;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 保存用户
    public Long save(User user){
        Long id = userService.save(user);
        return id;
    }


    // 根据手机查找用户
    public User findByMobile(String mobile){
        User user = userService.findByMobile(mobile);
        return user;
    }



    //发送验证码
    public void sendCode(String phone) {
        //1.生成随机验证码
        String code = RandomUtil.randomNumbers(6);

        // TODO 以后项目上线了,删除
        code = "123456";

        //2.调用阿里云模板发送短信
        // TODO 以后项目上线了,开启注释
        //smsTemplate.sendSms(phone,code);

        //3.将验证码保存到redis中,时效5分钟  //  sms:13600136000 = 123456
        stringRedisTemplate.opsForValue().set("sms:"+phone,code, Duration.ofMinutes(5));
    }


    //注册或登陆
    public ResponseEntity regAndLogin(Map<String, String> map) {
        //1.获取用户提交过来的手机号和验证码
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");

        //2.判断验证码是否和redis中的一致,若不一致,返回401
        String redisCode = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);

        //if(verificationCode != null && verificationCode.equals(redisCode)){}

        if (!StrUtil.equals(verificationCode,redisCode)) {
            //return ResponseEntity.status(500).body("你输入的验证码无效");
            return ResponseEntity.status(500).body(ErrorResult.codeError());
        }

        //3.通过手机号判断用户是否存在
        User user = userService.findByMobile(phone);
        Boolean isNew;
        if (user != null) {
            //3.1若存在,是老用户
            isNew = false;
        }else {
            //3.2若不存在,是新用户,调用service完成保存操作
            isNew = true;

            //构造用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long id = userService.save(user);

            //别忘记将用户的id设置上去
            user.setId(id);
        }

        //4.生成token,(id和手机号)
        user.setPassword(null);//出去关键数据
        Map<String, Object> userMap = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(userMap);

        //5.为了避免每次都解析token,将token作为key,用户的json数据做为value,放入redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token, JSON.toJSONString(user),Duration.ofDays(30));

        //5.1 从redis中把验证码删除
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);

        //6.将token和是否新用户放入map中直接返回
        HashMap<String, Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("isNew",isNew);
        return ResponseEntity.ok(resultMap);
    }
}
